<template>
  <div class="header" v-if="loading">
    <a-space :size="12" direction="vertical" align="center" >
      <a-avatar :size="64">
        <template #trigger-icon>
          <icon-camera />
        </template>
        <img :src="userInfo.avatarUrl" />
      </a-avatar>
      <a-typography-title :heading="6" style="margin: 0">
        {{ userInfo.nickName }}
      </a-typography-title>
      <div class="user-msg">
        <a-space :size="18">
          <div>
            <icon-user />
            <a-typography-text>{{ userInfo.realName }}</a-typography-text>
          </div>
      
          <div>
            <icon-location />
            <a-typography-text>{{ userInfo.city}}</a-typography-text>
          </div>
          
        </a-space>
      </div>
          <div>
            <a-typography-text>{{ userInfo.motto}}</a-typography-text>
          </div>
          <div>
            <a-button type="text" @click="handleClick">修改个人信息</a-button>
            <!-- <a-button type="text" @click="handleClick2">上传头像</a-button> -->

          </div>

            <a-modal v-model:visible="visible" @ok="handleOk" @cancel="handleCancel">
              <template #title>
                编辑个人信息
              </template>
              <div>
                  <a-form :model="form" :style="{width:'450px'}" @submit="handleSubmit">
                    <a-form-item field="name" label="昵称：">
                      <a-input v-model="form.nickName" placeholder="请输入新昵称" />
                    </a-form-item>
                    <a-form-item field="post" label="真实姓名：">
                      <a-input v-model="form.realName" placeholder="请输入真实姓名" />
                    </a-form-item>
                    <a-form-item field="city" label="所在城市：">
                      <a-input v-model="form.city" placeholder="请输入所在城市" />
                    </a-form-item>
                    <a-form-item field="motto" label="个性签名：">
                      <a-input v-model="form.motto" placeholder="请输入个性签名" />
                    </a-form-item>
                    <a-form-item>
                      <a-button html-type="submit">提交修改</a-button>
                    </a-form-item>
                  </a-form>
              </div>
            </a-modal>

            
            <a-modal v-model:visible="visible2" @ok="handleOk2" @cancel="handleCancel2">
              <template #title>
                上传头像
              </template>
              <div>
                   <a-space direction="vertical" :style="{ width: '100%' }" aling="center">
                      <a-upload
                        action="/"
                        :fileList="file ? [file] : []"
                        :show-file-list="false"
                        @change="onChange"
                        @progress="onProgress"
                      >
                        <template #upload-button>
                          <div
                            :class="`arco-upload-list-item${
                              file && file.status === 'error' ? ' arco-upload-list-item-error' : ''
                            }`"
                          >
                            <div
                              class="arco-upload-list-picture custom-upload-avatar"
                              v-if="file && file.url"
                            >
                              <img :src="file.url" />
                              <div class="arco-upload-list-picture-mask">
                                <IconEdit />
                              </div>
                              <a-progress
                                v-if="file.status === 'uploading' && file.percent < 100"
                                :percent="file.percent"
                                type="circle"
                                size="mini"
                                :style="{
                                  position: 'absolute',
                                  left: '50%',
                                  top: '50%',
                                  transform: 'translateX(-50%) translateY(-50%)',
                                }"
                              />
                            </div>
                            <div class="arco-upload-picture-card" v-else>
                              <div class="arco-upload-picture-card-text">
                                <IconPlus />
                                <div style="margin-top: 10px; font-weight: 600">Upload</div>
                              </div>
                            </div>
                          </div>
                        </template>
                      </a-upload>
                    </a-space>
              </div>
            </a-modal>
  

    </a-space>
  </div>
</template>

<script lang="ts" setup>
import IconEdit from '@arco-design/web-vue/es/icon/icon-edit';
import IconPlus from '@arco-design/web-vue/es/icon/icon-plus';
import { removeMyInterceptor } from '@/api/interceptor';
import { useUserStore } from '@/store';
import { Message } from '@arco-design/web-vue';
import axios from 'axios';
import { nextTick, reactive, ref } from 'vue';
const loading = ref(true);

    const visible = ref(false);
    const visible2 = ref(false);

    const handleClick = () => {
      visible.value = true;
    };
    const handleOk = () => {
      visible.value = false;
    };
    const handleCancel = () => {
      visible.value = false;
    }
    const handleClick2 = () => {
      visible2.value = true;
    };
      const file = ref();

    const onChange = (_:any, currentFile:any) => {
      file.value = {
        ...currentFile,
        // url: URL.createObjectURL(currentFile.file),
      };
    };
    const onProgress = (currentFile:any) => {
      file.value = currentFile;
    };
    const handleOk2 = () => {
      visible2.value = false;
      Message.info(file.value)
      console.log('file',file.value.url)
     
      var formdata = new FormData();
      var link;
      formdata.append("file", file.value.url);
      console.log('formdata',formdata);
      removeMyInterceptor();
      axios({
        url: 'user/avatarUpload',
        method: 'post',
        data: formdata,
        // dataType: "json",
        // cache: false,
        // processData: false,
        // headers: {'Content-Type': 'multipart/form-data'},
      }).then(res => {
            // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
            if (res.data.code === 0) {
              link = res.data.data
              // const userInfo = user.getters.getUser(user.state());
              removeMyInterceptor();
              axios({
                method: 'post',           /* 指明请求方式，可以是 get 或 post */
                url: 'user/avatarModify',       /* 指明后端 api 路径，由于在 main.js 已指定根路径，因此在此处只需写相对路由 */
                data:({
                  userID:localStorage.getItem('id'),
                  avatarUrl:link
                })
              })
                  .then( res => {
                    if (res.data.code === 0) {
                                      Message.success("更改成功")
                    }else{
                          console.log('失败');
                            Message.error(res.data.description)
                    }
                            }).catch(function () {
                          console.log('请求失败');
                        });
          }});
    }
    const handleCancel2 = () => {
      visible2.value = false;
    }
    let userInfo = {
        avatarUrl:'',
        city:'',
        realName:'',
        nickName:'',
        motto:'',
      };
    const form = reactive({
     avatarUrl:userInfo.avatarUrl,
      city:userInfo.city,
      realName:userInfo.realName,
      nickName:userInfo.nickName,
      motto:userInfo.motto,
    })
            console.log('form',form)
    const handleSubmit = (data:any) => {
      console.log(data)
      removeMyInterceptor();
        axios({
          method: 'post',           /* 指明请求方式，可以是 get 或 post */
          url: 'user/modify',       /* 指明后端 api 路径，由于在 main.js 已指定根路径，因此在此处只需写相对路由 */
          data: ({      /* 需要向后端传输的数据，此处使用 qs.stringify 将 json 数据序列化以发送后端 */
            userID:localStorage.getItem('id'),
            nickName:form.nickName,
            realName:form.realName,
            email:localStorage.getItem('email'),
            city:form.city,
            motto:form.motto
          })
        }).then(function (response) {
          console.log('请求成功');
          console.log(response.data)
          // console.log(localStorage.getItem('email'))
          if (response.data.code === 0) {
            // userInfo = response.data.data;
            // console.log('用户信息',userInfo)
            Message.success('修改成功')
          } else {
            console.log('失败');
            Message.error(response.data.description)
          }
        }).catch(function () {
          console.log('请求失败');
        });

    }
  
    const uploadAvatar = ()=>{

    }
    
   removeMyInterceptor();
        axios({
          method: 'post',           /* 指明请求方式，可以是 get 或 post */
          url: 'user/userInfo',       /* 指明后端 api 路径，由于在 main.js 已指定根路径，因此在此处只需写相对路由 */
          data: ({      /* 需要向后端传输的数据，此处使用 qs.stringify 将 json 数据序列化以发送后端 */
            userID:localStorage.getItem('id')
          })
        }).then(function (response) {
          console.log('请求成功');
          console.log(response.data)
        
          // console.log(localStorage.getItem('email'))
          if (response.data.code === 0) {
            userInfo = response.data.data;
            console.log('用户信息',userInfo)
            setTimeout(function() {   loading.value = false;
            nextTick(() => {
              loading.value = true;
            });}, 3000);  //5秒后将会调用执行remind()函数
            console.log('userinfo',userInfo)
          //  form.
            form.avatarUrl=userInfo.avatarUrl,
              form.city=userInfo.city,
              form.realName=userInfo.realName,
              form.nickName=userInfo.nickName,
              form.motto=userInfo.motto;
               loading.value = false;
                nextTick(() => {
                  loading.value = true;
                });
                console.log('form',form);
          } else {
            console.log('失败');
            Message.error(response.data.description)
          }
        }).catch(function () {
          console.log('请求失败');
        });

//  onMunted() {
//     this.$nextTick(()=>{
//       console.log('mounted')


//   }
</script>


<style scoped lang="less">
  .header {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 204px;
    color: var(--gray-10);
    background: url(//p3-armor.byteimg.com/tos-cn-i-49unhts6dw/41c6b125cc2e27021bf7fcc9a9b1897c.svg~tplv-49unhts6dw-image.image)
      no-repeat;
    background-size: cover;
    border-radius: 4px;

    :deep(.arco-avatar-trigger-icon-button) {
      color: rgb(var(--arcoblue-6));

      :deep(.arco-icon) {
        vertical-align: -1px;
      }
    }
    .user-msg {
      .arco-icon {
        color: rgb(var(--gray-10));
      }
      .arco-typography {
        margin-left: 6px;
      }
    }
  }
</style>
